# This code replicates Table A1 and Figure A3

library(readxl)
library(magrittr)
library(dplyr)
library(estimatr)
library(xtable)
library(sf)


assign <- read.csv("data/CuadranteTreatment.csv")
cov_labs <- read_xlsx("data/covariate_labs.xlsx")

# Table A1 ----------------------------------------------------------------
## corresponds to treatment conditions in survey data
assign %<>%
  mutate(Z = ifelse(treatment == 2, "Control",
                    ifelse(treatment == 1, "Meetings + Flyers",
                           ifelse(treatment == 3, "Meetings", "Flyers"))),
         Z = factor(Z, levels = c("Control", "Meetings", "Flyers", "Meetings + Flyers")))
## calculate quantities in balance table for each pre-treatment covariate
get_bal_tab <- function(varname){
  eq <- paste0(varname, " ~ Z")
  reg <- lm_robust(as.formula(eq), data = assign)
  p <- pf(reg$fstatistic[1], reg$fstatistic[2], reg$fstatistic[3], lower.tail = F)
  
  output <- round(c(as.vector(t(as.matrix(summary(reg)$coef[2:4,1:2]))), 
    coef(reg)[1], 
    sd(assign[assign$Z == "Control",varname]), 
    p),3)
  names(output) <- c("beta_m", "se_m", "beta_f", "se_f", "beta_mf", "se_mf", "ctrl_mean", "ctrl_sd", "p")
  return(output)  
}
## generates the table and covariate labels
bal_tab <- do.call("rbind", lapply(names(assign)[4:43], get_bal_tab))
table_a1 <- left_join(cov_labs,
  as.data.frame(bal_tab) %>%
    mutate(row_name = names(assign)[4:43])) %>%
  filter(row_name != "jefeh_obre") %>% # unclear what this variable measures
  select(-row_name) 

## save table
write(print(xtable(table_a1), include.rownames = F), file = "results/Table_A1.tex")



# Figure A3 ---------------------------------------------------------------

cuadrantes <- st_read(dsn = "data/cuadrante_shapefiles/", 
                      layer = "cuaranteswgs84 (2)")
manzs <- st_read(dsn = "data/cuadrante_shapefiles/", 
                      layer = "center_manzana2")
sf_use_s2(FALSE)

# crop spatial polygons
cuad_ss <- st_crop(cuadrantes, 
                   xmin = -75.58, xmax = -75.54,
                   ymin = 6.235, ymax = 6.265)
manz_ss <- st_crop(manzs, 
                        xmin = -75.58, xmax = -75.54,
                        ymin = 6.235, ymax = 6.265)
core_ss <- subset(manz_ss, keymanzana == 1)


pdf("results/Figure_A3.pdf", width = 4, height = 3)
par(mar=rep(0, 4),mai=rep(0, 4), xpd = NA) 
plot(st_geometry(manz_ss), border = "blue", lwd = .05)
plot(st_geometry(core_ss), border = "red", add = T, lwd = 1)
plot(st_geometry(cuad_ss), border = "black", lwd = 1.25, add = T)
dev.off()
